<template>
  <view class="page-container">
    <u-navbar title="个人信息" placeholder @leftClick="back" :border="false" :shadow="true"></u-navbar>
    <view class="container">
      <!-- 渐变背景 -->
      <view class="gradient-bg"></view>

      <!-- 用户卡片 -->
      <view class="user-card fade-overlay">
        <view class="user-header">
          <view class="user-avatar">
            <image v-if="detailsItem.img_url" class="avatar-img" :src="detailsItem.img_url" mode="aspectFill"></image>
            <view v-else class="text">{{ getUserName(detailsItem.worker_name) }}</view>
          </view>
          <view class="user-name">{{ detailsItem.worker_name }}</view>
        </view>

        <view class="company-info">
          <view class="company-name">江苏绿港现代农业发展股份有限公司</view>
          <view class="company-tag">高级认证</view>
        </view>
      </view>

      <!-- 底部公司名称 -->
      <view class="section-title">江苏绿港现代农业发展股份有限公司</view>

      <!-- 信息卡片 -->
      <view class="info-content">
        <view class="info-card">
          <view class="info-item">
            <text class="item-label">企业/组织</text>
            <text class="item-value">江苏绿港现代农业发展股份有限公司</text>
          </view>
          <view class="info-item">
            <text class="item-label">姓名</text>
            <text class="item-value">{{ detailsItem.worker_name }}</text>
          </view>
          <view class="info-item">
            <text class="item-label">部门</text>
            <text class="item-value">{{ detailsItem.new_depart_name }}</text>
          </view>
          <view class="info-item">
            <text class="item-label">职位</text>
            <text class="item-value">{{ detailsItem.pos_name }}</text>
          </view>
          <view class="info-item">
            <text class="item-label">手机号</text>
            <text class="item-value" @click="showCopyMenu">{{ detailsItem.phone }}</text>
          </view>
        </view>

        <view class="info-card">
          <view class="info-item">
            <text class="item-label">入职天数</text>
            <text class="item-value">今天是我来公司的{{ work_days }}天</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="judgeInfo" class="action-bar">
      <!-- <button class="action-btn float-btn" type="primary" @click="SendamessageClk">
          <image  class="TabItemICon" src="@/static/icon/MessageBlue.svg"></image>
        发消息
      </button> -->
      <u-button icon="more-circle-fill" icon-color="#fff" color="linear-gradient(135deg, #4889f6, #6ab1ff)"
        style="margin-right: 20rpx;" @click="SendamessageClk">
        发消息
      </u-button>
      <u-button icon="phone-fill" icon-color="#fff" color="linear-gradient(135deg, #4889f6, #6ab1ff)"
        @click="callPhone(detailsItem.phone)">
        拨打电话
      </u-button>
    </view>
  </view>
</template>

<script setup>
import { addressBookworkerlist } from '@/apis/addressBook/details.js';
import { chatApi } from '@/apis/cloud/chat';
import { useChatStore, useGroupStore, useSearchStore, useSocketStore, useUserStore } from '@/pinia-store/user';
import { objectToFormData } from "@/utils/chat";
import { getCurrentInstance, onMounted, ref } from "vue";

const detailsItem = ref({});
const detailsObj = ref({});
const work_days = ref(0)
const userStore = useUserStore();
const chatStore = useChatStore();
const groupStore = useGroupStore();
const searchStore = useSearchStore();
const socketStore = useSocketStore();
const judgeInfo = ref(true)
// 发消息
const SendamessageClk = async () => {
  const params = {
    data: {
      myAccount: userStore.user.chat_account,
      token: userStore.user.token,
      account: userStore.user.chat_account,
      friends: {
        friend_account: detailsItem.value.chat_account,
        friend_username: detailsItem.value.worker_name,
        friend_phone: detailsItem.value.phone,
      }
    },
    url: 'index.php/users/Index/updateMyFriends'
  }

  const msg = await chatApi(userStore.user.token, objectToFormData(params));

  if (msg.code === 200) {
    let person = searchStore.$state.person || []
    if (person) {
      const index = person.findIndex(historyItem => historyItem.id === detailsItem.value.id)
      if (index !== -1) {
        person.splice(index, 1)
      }
      person.unshift(detailsItem.value)
      if (person.length > 20) {
        person.pop()
      }
    }
    socketStore.$state.nowDialogId = detailsItem.value?.dialog_id
    uni.setStorageSync('nowDialogId', detailsItem.value?.dialog_id)
    searchStore.setPerson(person)
    chatStore.setChat(msg.data)
    uni.setStorageSync('friend', JSON.stringify(msg.data))
    uni.redirectTo({
      url: '/pages/chat/message/chat/chat'
    })
  }

};
// 返回
const back = () => {
  uni.navigateBack({ delta: 1 });
};
// 复制手机号
const showCopyMenu = () => {
  uni.showActionSheet({
    itemList: ['复制手机号'],
    success: (res) => {
      if (res.tapIndex === 0) {
        copyPhone(); // 执行复制
      }
    }
  });
};

const copyPhone = () => {
  uni.setClipboardData({
    data: detailsItem.value.phone,
    success: () => {
      uni.showToast({
        title: '手机号已复制',
        icon: 'none'
      });
    }
  });
};

// 名称处理
const getUserName = (name) => {
  if (name?.length === 0) {
    return '';
  } else if (name?.length <= 2) {
    return name;
  } else if (name?.length >= 3) {
    return name.substring(name.length - 2);
  }
}


onMounted(() => {
	const instance = getCurrentInstance().proxy;
	const eventChannel = instance.getOpenerEventChannel();
	eventChannel.on('details', async function (data) {
		uni.showLoading({
			title: '加载中...'
		});
		detailsObj.value = data.item;
		if (data.item.id == userStore.user.worker_id) {
			judgeInfo.value = false
		} else {
			judgeInfo.value = true
		}
		
		let res = await addressBookworkerlist({
			token: userStore.user.token,
			worker_name: data.item.name || data.item.username || data.item.worker_name,
			page: 1,
			row: 10,
			// worker_id: data?.item?.id,
		});
		uni.hideLoading()
		if (res.status == 1) {
			if (res.data.length > 0) {
				detailsItem.value = res.data[0];
				const parseDate = (str) => {
					if (!str) return new Date(NaN);
					return new Date(str.replace(/-/g, '/'));
				};
				const date1 = parseDate(detailsItem.value.entry_date);
				const date2 = new Date();
				if (!isNaN(date1.getTime())) {
					const diffDays = Math.floor((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
					work_days.value = diffDays;
				} else {
					work_days.value = 0; // 无效日期，默认0天
					console.warn('entry_date 无法解析:', detailsItem.value.entry_date);
				}
			} else {
				uni.$u.toast(res.status.msg || '查看失败，请稍后重试222');
			}
		} else {
			uni.$u.toast(res.status.msg || '查看失败，请稍后重试111');
		}
	});
});

// 权限状态跟踪
const permissionDeniedAlways = ref(false)

/**
 * 拨打电话（核心函数）
 * @param {string} phoneNumber - 要拨打的电话号码
 */
const callPhone = async (phoneNumber) => {
  try {
    // #ifdef APP-PLUS
    await checkCallPermission()
    // #endif

    uni.makePhoneCall({
      phoneNumber,
      success: () => console.log('拨号成功'),
      fail: (err) => {
        console.error('拨号失败:', err)
        handleManufacturerPermission(phoneNumber)
      }
    })
  } catch (error) {
    console.error(error)
    permissionDeniedAlways.value = error === 'PERMISSION_DENIED_ALWAYS'
    permissionDeniedAlways.value
      ? showPermissionGuide()
      : uni.showToast({ title: '拨号权限被拒绝', icon: 'none' })
  }
}

/**
 * 检查并申请电话权限（Android专用）
 */
const checkCallPermission = () => {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    plus.android.checkPermission('android.permission.CALL_PHONE',
      (e) => {
        if (e.success) {
          resolve()
        } else {
          plus.android.requestPermissions(
            ['android.permission.CALL_PHONE'],
            (result) => {
              const granted = result.granted ||
                (result.denied.length === 0 &&
                  result.deniedAlways.length === 0)
              granted ? resolve() : reject('PERMISSION_DENIED')
            },
            (err) => reject(err)
          )
        }
      },
      (err) => reject(err)
    )
    // #endif

    // #ifdef APP-PLUS
    resolve() // iOS无需动态申请
    // #endif

    // #ifndef APP-PLUS
    resolve() // 非APP端无需处理
    // #endif
  })
}

/**
 * 处理国产手机特殊权限需求
 * @param {string} phoneNumber - 要拨打的电话号码
 */
const handleManufacturerPermission = (phoneNumber) => {
  // 检测小米/华为等需要额外权限的厂商
  if (['xiaomi', 'huawei'].includes(plus.os.vendor?.toLowerCase())) {
    uni.showModal({
      title: '权限提示',
      content: '请在系统设置中开启「电话」和「后台弹出界面」权限',
      confirmText: '去设置',
      success: (res) => res.confirm && plus.runtime.openSettings()
    })
  } else {
    // 通用备选方案：直接调用系统拨号界面
    plus.runtime.openURL(`tel:${phoneNumber}`)
  }
}

/**
 * 显示权限引导弹窗
 */
const showPermissionGuide = () => {
  uni.showModal({
    title: '权限被永久拒绝',
    content: '需要电话权限才能拨号，请前往应用设置手动开启',
    confirmText: '去设置',
    success: (res) => res.confirm && plus.runtime.openSettings()
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  position: relative;
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.container {
  flex: 1;
  position: relative;
  padding-bottom: 120rpx;
  overflow-y: auto;
}

.gradient-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  background: url('../../../static/work-home/detailsYq.png') no-repeat center top / cover;
  z-index: 0;
}


.user-card {
  position: relative;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx 30rpx;
  margin: 280rpx 24rpx 10rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 1;

  .user-header {
    display: flex;
    align-items: center;
    height: 80rpx;

    .user-avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 10%;
      border: 4rpx solid #fff;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      position: absolute;
      top: -80rpx;
      left: 30rpx;

      .avatar-img {
        width: 100%;
        height: 100%;
        border-radius: 10%;
      }

      .text {
        height: 160rpx;
        border-radius: 10%;
        background: #377fff;
        text-align: center;
        color: #ffffff;
        line-height: 160rpx;
      }
    }

    .user-name {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-left: 190rpx;
      margin-top: -75rpx;
    }
  }

  .company-info {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .company-name {
      font-size: 28rpx;
      color: #4889f6;
      font-weight: 500;
    }

    .company-tag {
      font-size: 22rpx;
      color: #ff9900;
      background-color: #fff8e6;
      border-radius: 8rpx;
      padding: 4rpx 12rpx;
      margin-left: 16rpx;
      border: 1rpx solid #ffe7a7;
    }
  }
}

.section-title {
  font-size: 28rpx;
  color: #909399;
  padding: 20rpx 40rpx;
  text-align: left;
  margin-bottom: 10rpx;
}

.info-content {
  padding: 0 24rpx;
}

.info-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 28rpx 30rpx;
    border-bottom: 1rpx solid #f5f7fa;

    &:last-child {
      border-bottom: none;
    }

    .item-label {
      font-size: 28rpx;
      color: #909399;
      width: 160rpx;
      flex-shrink: 0;
    }

    .item-value {
      font-size: 28rpx;
      color: #333;
      flex: 1;
      text-align: right;
      word-break: break-all;
    }
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  border-radius: 20rpx;
  margin-left: 10rpx;
  margin-right: 10rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);

  .TabItemICon {
    position: relative;
    top: 4rpx;
    width: 1rem;
    height: 1rem;
  }

  .action-btn {
    margin-left: 15rpx;
    margin-right: 15rpx;
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    background: linear-gradient(135deg, #4889f6, #6ab1ff);
    font-size: 32rpx;

    &::after {
      border: none;
    }
  }
}


.float-btn {
  height: 96rpx;
  line-height: 96rpx;
  border-radius: 48rpx;
  background-color: #4889f6;
  font-size: 34rpx;
  color: white;
  border: none;
  box-shadow: 0 8rpx 24rpx rgba(72, 137, 246, 0.4);
  transition: all 0.2s;
}

.float-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(72, 137, 246, 0.4);
}
</style>
